#!/usr/bin/python
# -*- coding: UTF-8 -*-
from PIL import Image, ImageDraw, ImageFont
import random
'''
def getRandomColor():
        #获取一个随机颜色(r,g,b)格式的
        c1 = random.randint(0,255)
        c2 = random.randint(0,255)
        c3 = random.randint(0,255)
        return (c1,c2,c3)
'''
def getRandomStr():
        '''获取一个随机字符串，每个字符的颜色也是随机的'''
        random_num = str(random.randint(0, 9))
        random_low_alpha = chr(random.randint(97, 122))
        random_upper_alpha = chr(random.randint(65, 90))
        random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
        return random_char

class ValidCodeImg:
    def __init__(self,width=85,height=26,code_count=4,font_size=25,point_count=20,line_count=2,img_format='png'):
        '''
        可以生成一个经过降噪后的随机验证码的图片
        :param width: 图片宽度 单位px
        :param height: 图片高度 单位px
        :param code_count: 验证码个数
        :param font_size: 字体大小
        :param point_count: 噪点个数
        :param line_count: 划线个数
        :param img_format: 图片格式
        '''
        self.width = width
        self.height = height
        self.code_count = code_count
        self.font_size = font_size
        self.point_count = point_count
        self.line_count = line_count
        self.img_format = img_format
 
    def getValidCodeImg(self):
        image = Image.new('RGB',(self.width,self.height),(255,255,255))
        draw = ImageDraw.Draw(image)
        font=ImageFont.truetype("arial.ttf",size=self.font_size)# font字体对象

        temp = []
        for i in range(self.code_count):
                random_char = getRandomStr()
                #random_color  = getRandomColor()
                random_color = (0,0,0)
                draw.text((2+i*17,0),random_char , random_color, font = font)
                temp.append(random_char)
        valid_str = "".join(temp)
 
        # 噪点噪线
        for i in range(self.line_count):# 划线
                x1=0
                x2=self.width
                y1=self.height/2
                y2=random.uniform(self.height/2,self.height*3/4)
                draw.line((x1,y1,x2,y2),fill=(0,0,0))
        '''
        for i in range(self.point_count):# 画点
            draw.point([random.randint(0, self.width), random.randint(0, self.height)], fill=getRandomColor())
            x = random.randint(0, self.width)
            y = random.randint(0, self.height)
            draw.arc((x, y, x + 4, y + 4), 0, 90, fill=getRandomColor())
        '''
        # 在内存生成图片
        from io import BytesIO
        f = BytesIO()
        image.save(f, self.img_format)
        data = f.getvalue()
        f.close()

        return data,valid_str
 
if __name__ == '__main__':
        for i in range(0,1000):
                img = ValidCodeImg()
                data, valid_str = img.getValidCodeImg()
                f = open('D:\\PythonProject\\vc_recognition_test\\vc_base\\' + valid_str + '.jpg', 'wb')
                f.write(data)
                f.close()
